package com.cathyjava.crawl.service.impl;

import com.cathyjava.crawl.service.CrawService;
import org.apache.commons.lang3.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenjing
 * @date 2021/4/16
 */
@Service
public class CrawServiceImpl implements CrawService {
    @Autowired
    RedisTemplate redisTemplate;

    private static ConcurrentHashMap<Integer, Byte> map = new ConcurrentHashMap<>();

    @Override
    public void openOrCloseCrawl(Integer sourceId, Byte sourceStatus) {
        String cacheKey = "thread:" + sourceId;
        Byte currentStatus = map.get(sourceId);

        //停止
        if (sourceStatus == (byte) 0) {
            //当前启动中，需要停止线程
            if (currentStatus != null && currentStatus.equals((byte) 1)) {
                Set<Long> threadIds = (Set<Long>) redisTemplate.opsForValue().get(cacheKey);
                for (Long threadId : threadIds) {
                    Thread t = ThreadUtils.findThreadById(threadId);
                    if (t != null && t.isAlive()) {
                        t.interrupt();
                    }
                }
                redisTemplate.delete(cacheKey);
            }
        }
        //启动
        else {
            //当前未启动，需要启动线程
            if (currentStatus == null || currentStatus.equals((byte) 0)) {
                Set<Long> threadIds = new HashSet<>();
                for (int i = 0; i < 1; i++) {
                    MyThread t = new MyThread(sourceId.toString());
                    threadIds.add(t.getId());
                    t.start();
                }

                redisTemplate.opsForValue().set(cacheKey, threadIds);
                System.out.println("sourceid=" + sourceId + " threadids=" + Arrays.toString(threadIds.toArray()));
            }
        }

        map.put(sourceId, sourceStatus);
    }
}

class MyThread extends Thread {
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        int n = 0;
        while (!isInterrupted()) {
            n++;
            System.out.println("Hello " + name + "-" + n);
        }
    }
}
